package com.ssy.invoicing.order.comtroller;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.ssy.invoicing.common.constant.Constant;
import com.ssy.invoicing.common.controller.BaseController;
import com.ssy.invoicing.common.util.DateUtil;
import com.ssy.invoicing.common.util.StringUtil;
import com.ssy.invoicing.customer.bean.CustomerBean;
import com.ssy.invoicing.customer.service.CustomerService;
import com.ssy.invoicing.dao.support.BaseSqlDao.SplitPageResult;
import com.ssy.invoicing.order.bean.SaleOrderBean;
import com.ssy.invoicing.order.bean.SaleProductBean;
import com.ssy.invoicing.order.bean.vo.OrderVo;
import com.ssy.invoicing.order.service.OrderService;

/**
 * 销售订单Controller
 * Comment of OrderController
 * @author suoyao.shen
 */
@Controller
@RequestMapping("invoicing")
public class OrderController extends BaseController {
    Logger logger = LoggerFactory.getLogger(OrderController.class);
    
    @Resource(name="orderService")
    private OrderService orderService;
    
    @Resource(name="customerService")
    private CustomerService customerService;
    
    /**
     * @return
     */
    @RequestMapping("addOrder")
    public ModelAndView addOrder(ModelMap model) {
        List<CustomerBean> demandCustomer = customerService.queryCustomerByType(Constant.DEMAND_UNIT);
        List<CustomerBean> finalCustomer = customerService.queryCustomerByType(Constant.FINAL_UNIT);
        model.put("demandCustomer", demandCustomer);
        model.put("finalCustomer", finalCustomer);
        return new ModelAndView("pages/order/add");
    }
    
    /**
     * @param vo
     * @param model
     * @return
     */
    @RequestMapping("listOrder")
    public ModelAndView listOrder(OrderVo vo, ModelMap model) {
        try {
            SplitPageResult spr = orderService.queryOrderList(vo);
            model.put("pagination", spr.getPagination());
            model.put("orderList", spr == null ? null : spr.getResult());
            model.put("vo", vo);
        } catch (SQLException e) {
            logger.error("query Order list fail.",e);
            return new ModelAndView("pages/error/err");
        }
        return new ModelAndView("pages/order/list");
    }

    /**
     * @param order
     * @param pname
     * @param pattern
     * @param model
     * @return
     */
    @RequestMapping("saveOrder")
    public ModelAndView saveOrder(SaleOrderBean order, String[] pname, String[] pattern,
                                  Integer[] saleCount, String[] salePrice, String[] totalPrice,
                                  Date[] deliverTime, String[] remark, ModelMap model) {
        orderService.saveOrder(order, pname, pattern,saleCount,salePrice,totalPrice,deliverTime,remark);
        return new ModelAndView("redirect:listOrder.htm");
    }
    
    /**
     * Ajax根据销售订单加载产品
     * @param orderId
     * @return
     */
    @RequestMapping("loadProject")
    @ResponseBody
    public List<SaleProductBean> loadProject(Integer orderId) {
        List<SaleProductBean> productList = orderService.loadNoPurchaseProductByOrderId(orderId);
        //return JsonUtil.toJsonString(productList);
        return productList;
    }
    
    /**
     * 销售订单详情
     * @author suoyao.shen
     * @param orderId
     * @return
     */
    @RequestMapping("detailOrder")
    public ModelAndView detailOrder(OrderVo vo, Integer orderId, ModelMap model) {
        /*
         * 获得销售订单详情
         */
        SaleOrderBean order = orderService.getOrderDetail(orderId);
        /*
         * 获得销售订单下的所有产品列表
         */
        List<SaleProductBean> productList = orderService.loadProductByOrderId(orderId);
        model.put("order", order);
        model.put("productList", productList);
        model.put("vo", vo);
        return new ModelAndView("pages/order/detail");
    }
    
    /**
     * 追加产品
     * @return
     */
    @RequestMapping("additionalOrder")
    public ModelAndView additionalOrder(Integer orderId, ModelMap model) {
        SaleOrderBean order = orderService.getOrderDetail(orderId);
        model.put("order", order);
        return new ModelAndView("pages/order/additional");
    }
    
    /**
     * 保存追加的产品
     * @author suoyao.shen
     * @param orderId
     * @param pname
     * @param pattern
     * @param model
     * @return
     */
    @RequestMapping("saveAdditionalOrder")
    public ModelAndView saveAdditionalOrder(Integer orderId, String[] pname, String[] pattern,
                                            Integer[] saleCount, String[] salePrice,
                                            String[] totalPrice, Date[] deliverTime,
                                            String[] remark, ModelMap model) {
        List<SaleProductBean> productList = new ArrayList<SaleProductBean>();
        for (int i = 0; i < pname.length; i++) {
            productList.add(new SaleProductBean(pname[i], pattern[i], saleCount[i], salePrice[i],
                    totalPrice[i], deliverTime[i], remark[i],orderId));
        }
        orderService.saveProductBatch(productList);
        return new ModelAndView("redirect:detailOrder.htm?orderId=" + orderId);
    }
    
    /**
     * 列出销售订单下的所有产品
     * @param orderId
     * @param model
     * @return
     */
    @RequestMapping("listProductByOrderId")
    public ModelAndView listProductByOrderId(Integer orderId,ModelMap model) {
        SaleOrderBean order = orderService.getOrderDetail(orderId);
        model.put("order", order);
        List<SaleProductBean> productList = orderService.loadProductByOrderId(orderId);
        model.put("productList", productList);
        return new ModelAndView("pages/order/productList");
    }
    
    /**
     * 删除产品信息
     * @author suoyao.shen
     * @param orderId
     * @param productId
     * @param model
     * @return
     */
    @RequestMapping("removeProduct")
    public ModelAndView removeProduct(Integer orderId, Integer[] productId, ModelMap model) {
        orderService.removeProduct(productId,orderId);
        return new ModelAndView("redirect:detailOrder.htm?orderId=" + orderId);
    }
    
    /**
     * 检查销售订单好是否已经存在
     * @param orderNumber
     * @return
     */
    @RequestMapping("checkOrderNumber")
    @ResponseBody
    public String checkOrderNumber(String orderNumber) {
        if (StringUtil.isEmpty(orderNumber)) {
            return "invalid";
        }
        boolean bool = orderService.checkHasOrderNumber(orderNumber);
        if (bool) {
            return "invalid";
        }
        return "success";
    }
    
    /**
     * 根据订单好删除订单及订单下的所有产品
     * @param orderId
     * @return
     */
    @RequestMapping("removeOrder")
    public ModelAndView removeOrder(Integer orderId) {
        orderService.removeOrder(orderId);
        return new ModelAndView("redirect:listOrder.htm");
    }
    
    /**
     * 导入销售订单
     * @return
     */
    @RequestMapping("importOrder")
    public ModelAndView importOrder(ModelMap model) {
        List<CustomerBean> demandCustomer = customerService.queryCustomerByType(Constant.DEMAND_UNIT);
        List<CustomerBean> finalCustomer = customerService.queryCustomerByType(Constant.FINAL_UNIT);
        model.put("demandCustomer", demandCustomer);
        model.put("finalCustomer", finalCustomer);
        return new ModelAndView("pages/order/uploadOrder");
    }
    
    /**
     * 导入Excel
     * @param request
     * @return
     */
    @RequestMapping(value="uploadOrder",method=RequestMethod.POST)
    @ResponseBody
    public String uploadOrder(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("Filedata");
        String orderNumber = multipartRequest.getParameter("orderNumber");
        String saleTime = multipartRequest.getParameter("saleTime");
        String demandUnit = multipartRequest.getParameter("demandUnit");
        String finalUnit = multipartRequest.getParameter("finalUnit");
        String excelFilePath = "";
        try {
            /*1、初始化订单对象*/
            SaleOrderBean order  = new SaleOrderBean(orderNumber,demandUnit,finalUnit,DateUtil.parseDate(saleTime, DateUtil.DATE_FORMAT));
            /*2、创建临时文件夹存储批次包*/
            File dirFile = new File(UUID.randomUUID().toString());
            /*4、开始上传文件写入到本地*/
            excelFilePath = saveFile(file,dirFile.getAbsolutePath(),new Date().getTime() + ".xls");
            orderService.importOrder(order, excelFilePath);
            return "success";
        } catch (IOException e) {
            logger.error("file upload failed io exception reson.",e);
            return "failed";
        } catch (Exception e) {
            logger.error("file upload failed unknow reson.",e);
            return "failed";
        } finally {
            try {
                FileUtils.forceDelete(new File(excelFilePath).getParentFile());
            } catch (IOException e) {
                logger.error("delete file failed.",e);
            }
        }
    }
    
    /**
     * 将上传的批次文件保存到服务器上,准备解压存储到KV
     * @param file
     * @param path
     * @param fileName
     * @throws IOException
     */
    private String saveFile(MultipartFile file,String path,String fileName) throws IOException {
        File filePath = new File(path);
        if(!filePath.exists()) {
            filePath.mkdirs();
        }
        String excelFiel = path + File.separator + fileName;
        // 写入文件 
        File fileAbsolutePath = new File(excelFiel);
        if(!fileAbsolutePath.exists()) {
            fileAbsolutePath.createNewFile();
        }
        //开始上传文件
        file.transferTo(fileAbsolutePath);
        return excelFiel;
    }
    
}
